package com.demo.config;

import com.alibaba.fastjson.JSON;
import com.demo.bean.User;
import org.springframework.lang.Nullable;
import org.springframework.web.servlet.AsyncHandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import redis.clients.jedis.Jedis;

import java.io.IOException;

import static com.demo.Tools.DateCompute.getNowTime;

/**
 * @author 李天航
 * 登录拦截器，放行逻辑
 */

public class LoginInterceptor implements AsyncHandlerInterceptor {
    /**
     *  拦截策略，默认true，返回false表示被拦截
     */
    final long MAX_ACCESS_TIME=200;
    final String loginUri="/user/login";
    final String registerUri="/user/add";
    /**
     * 前缀，配合userAccount
     */
    private final String sessionIdSuffix="-session";
    /**
     * 后缀，配合sessionId
     */
    private final String sessionIdPrefix="session-";

    private boolean preventAtack(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //防爬虫攻击，每0.2s只能访问一次
        HttpSession session=request.getSession();
        if(System.currentTimeMillis()-session.getLastAccessedTime()<MAX_ACCESS_TIME)
        {
            System.out.println(System.currentTimeMillis());
            System.out.println(session.getLastAccessedTime());
            response.getWriter().println("{\"status\":500,\"msg\":\"request too quickly\"}");
            return false;
        }
        return true;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //登录拦截的业务逻辑
        String uri=request.getRequestURI();
        System.out.println(getNowTime()+":"+request.getMethod()+" "+request.getRequestURI());

        if(loginUri.equals(uri)||registerUri.equals(uri)||registerUri.matches("/img*")) {
            return true;
        }
        Jedis jedis = new Jedis("127.0.0.1", 6379);
        jedis.auth("123456");
        HttpSession session=request.getSession();
        String cookie=session.getId();
        String userAccount = jedis.hget(sessionIdPrefix+cookie,"userAccount");
        if (userAccount != null) {
            userAccount=userAccount.substring(1,userAccount.length()-1);
            String nowSession=jedis.get(userAccount+sessionIdSuffix);
            nowSession=nowSession.substring(1,nowSession.length()-1);
            if(!nowSession.equals(cookie))
            {
                response.getWriter().println("{\"status\":500,\"msg\":\"this account has already login, please login again\"}");
                return false;
            }
            return true;
        }
        response.getWriter().println("{\"status\":500,\"msg\":\"please login first\"}");
        return false;
    }

    /**
     * 在请求最后后会执行这个方法
     */
    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler,
                         @Nullable Exception ex) throws Exception {
//        System.out.println("请求结束,调用afterCompletion方法");
    }

    /**
     *  controller方法执行完后会执行这个方法
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                            @Nullable ModelAndView modelAndView) throws Exception {
//        System.out.println("postHandle方法被执行");
    }

    /**
     *  所有工作都做完完后（包括出现异常后），最后都会执行这个方法
     */
    @Override
    public void afterConcurrentHandlingStarted(HttpServletRequest request, HttpServletResponse response,
                                                Object handler) throws Exception {
//        System.out.println("afterConcurrentHandlingStarted方法被执行");
    }
}
